package com.zjz.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

// sqlSessionFactory --> sqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 第一步--获取sqlSessionFactory对象

            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }//获取SqlSession连接

    public static SqlSession getSqlSession() {

/*        try(SqlSession sqlSession = sqlSessionFactory.openSession()){  // sqlSession 不是线程安全的
            return sqlSession;
        } // 此方法执行return后就会直接关闭sqlSession。。。导致后面获取不到sqlSession对象*/

       return sqlSessionFactory.openSession();
    }
}
